/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.dictionary;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.common.base.JsonAssist;
import com.je.common.base.constants.ConstantVars;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.mapper.query.Query;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.result.DirectJsonResult;
import com.je.common.base.util.ArrayUtils;
import com.je.common.base.util.StringUtil;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.meta.service.dictionary.MetaTreeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/je/meta/dictionary/tree")
public class DictionaryTreeController extends AbstractPlatformController {

    private static final int DEFAULT_LOAD_NUM = 10;

    @Autowired
    private MetaTreeService treeService;

    @RequestMapping(value = "/loadTree", method = RequestMethod.POST)
    public JSONArray loadTree(BaseMethodArgument param, HttpServletRequest request) {
        String strData = param.getStrData();
        String node = param.getNode();
        String excludes = param.getExcludes();
        JsonAssist jsonAssist = JsonAssist.getInstance();

        if (Strings.isNullOrEmpty(strData)) {
            return DirectJsonResult.buildArrayResult("[]");
        }

        if (StringUtil.isEmpty(node)) {
            node = ConstantVars.TREE_ROOT;
        }

        //只包含子项
        boolean onlyItem = param.getOnlyItem();

        //国际化
        boolean en = false;
        Cookie jeLang = org.springframework.web.util.WebUtils.getCookie(request, "je-local-lang");
        if (jeLang != null) {
            if ("en".equals(jeLang.getValue())) {
                en = true;
            }
        }

        //字典结果集
        List<JSONTreeNode> array = new ArrayList<>();

        //字典查询条件集合
        JSONArray jsonArray = JSON.parseArray(strData);
        if (jsonArray.size() > DEFAULT_LOAD_NUM) {
            throw new PlatformException(String.format("每次最多加载%s个字典", DEFAULT_LOAD_NUM), PlatformExceptionEnum.JE_CORE_DIC_UNKOWN_ERROR);
        }

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            obj.put("customQuery", param.buildQuery().getCustom());
            //是否异步
            boolean async = obj.getBoolean("async");
            if (ConstantVars.TREE_ROOT.equals(node)) {
                // 第一次请求
                if (async) {
                    array.addAll(treeService.loadAsynTree(obj, en, onlyItem));
                } else {
                    array.addAll(treeService.loadSyncTree(obj, en, onlyItem));
                }
            } else {
                // 第N次请求，只刷异步树
                array.addAll(treeService.loadAsynTree(obj, en, onlyItem));
            }
        }
        strData = jsonAssist.buildListPageJson((long) array.size(), array, excludes.split(ArrayUtils.SPLIT), false);
        return DirectJsonResult.buildArrayResult(strData);
    }

    /**
     * 加载三级联动字典数据(无缓存)
     */
    @RequestMapping(value = "/loadLinkTree", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult loadLinkTree(BaseMethodArgument param, HttpServletRequest request) {
        Query query = param.buildQuery();
        String ddCode = getStringParameter(request, "ddCode");
        String parentId = getStringParameter(request, "parentId");
        String parentCode = getStringParameter(request, "parentCode");
        String rootId = getStringParameter(request, "rootId");
        String paramStr = getStringParameter(request, "paramStr");
        boolean zwfFlag = "1".equals(getStringParameter(request, "zwfFlag"));
        // 国际化
        Boolean en = false;
        Cookie jeLang = org.springframework.web.util.WebUtils.getCookie(request, "je-local-lang");
        if (jeLang != null) {
            if ("en".equals(jeLang.getValue())) {
                en = true;
            }
        }

        //加载级联树形数据
        List<JSONTreeNode> jsonTreeNodes = treeService.loadLinkTree(ddCode, parentId, parentCode, rootId, paramStr, en, query);
        String strData = JsonAssist.getInstance().buildListPageJson((long) jsonTreeNodes.size(), jsonTreeNodes, new String[]{}, false);
        return BaseRespResult.successResult(DirectJsonResult.buildArrayResult(strData));
    }

    /**
     * 查询指定节点信息
     */
    @RequestMapping(value = "/findAsyncNodes", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult findAsyncNodes(BaseMethodArgument param, HttpServletRequest request) {
        String excludes = param.getExcludes();
        String queryType = getStringParameter(request, "type");
        String value = getStringParameter(request, "value");
        //字典相关信息
        String strData = param.getStrData();
        JSONArray jsonArray = JSON.parseArray(strData);

        List<JSONTreeNode> jsonTreeNodeList = new ArrayList();
        if (StringUtil.isEmpty(value) || jsonArray.isEmpty()) {
            //没有值直接返回空
            return BaseRespResult.successResult(jsonTreeNodeList, "");
        }

        //获取前端参数
        JSONObject ddConfig = jsonArray.getJSONObject(0);

        //国际化
        Boolean en = false;
        Cookie jeLang = org.springframework.web.util.WebUtils.getCookie(request, "je-local-lang");
        if (jeLang != null) {
            if ("en".equals(jeLang.getValue())) {
                en = true;
            }
        }
        List<JSONTreeNode> jsonTreeNodes = treeService.findAsyncNodes(ddConfig, queryType, value, en, true);
        return BaseRespResult.successResult(jsonTreeNodes, "");
    }

}
